<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\common\model;
use think\Validate;
use think\model\concern\SoftDelete;
use app\common\model\BookPlan as BookPlanModel;
use think\Db;
use think\facade\Log;

class PlanStudentRel extends Common
{ 
    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);

        $bookPlanModel = new BookPlanModel();
        $list = $bookPlanModel->alias('plan')
                ->field("distinct plan.plan_code, plan.plan_year, case when plan.plan_season = 1 then '春季' when plan.plan_season = 3 then '秋季' end plan_season, 
                    bm.bmdm as dept_id, bm.bmmc as dept_name, zy.zydm as specialty_id, zy.zymc as specialty_name, plan.plan_class_name, plan.plan_dir,
                    case when plan.plan_dir = 1 then '就业' when plan.plan_dir = 2 then '升学' when plan.plan_dir = 3 then '创业' end plan_dirName,
                    plan.plan_grade, plan.plan_degree_name, plan.plan_degree_id, if(IFNULL(rel.plan_code, 0) = 0, '未关联', '已关联') status")
                ->join('zlzhsf.pbmdm bm', 'bm.bmdm = plan.plan_dep_id')
                ->join('zlzhsf.pzydm zy', 'zy.zydm = plan.plan_specialty_id')
                ->leftjoin('plan_student_rel rel', 'plan.plan_code = rel.plan_code')
                ->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);
        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $listTotal = $bookPlanModel->alias('plan')
                ->field("distinct plan.plan_code, plan.plan_year, case when plan.plan_season = 1 then '春季' when plan.plan_season = 3 then '秋季' end plan_season, 
                    bm.bmdm as dept_id, bm.bmmc as dept_name, zy.zydm as specialty_id, zy.zymc as specialty_name, plan.plan_class_name, 
                    case when plan.plan_dir = 1 then '就业' when plan.plan_dir = 2 then '升学' when plan.plan_dir = 3 then '创业' end plan_dir,
                    plan.plan_grade, plan.plan_degree_name, plan.plan_degree_id")
                ->join('zlzhsf.pbmdm bm', 'bm.bmdm = plan.plan_dep_id')
                ->join('zlzhsf.pzydm zy', 'zy.zydm = plan.plan_specialty_id')
                ->where($tableWhere['where'])->select();

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = count($listTotal);
        $re['data'] = $data;

        return $re;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['year']) && $post['year'] != ""){
            $where[] = ['plan.plan_year', 'eq', $post['year']];
        }
        if(isset($post['season']) && $post['season'] != ""){
            $where[] = ['plan.plan_season', 'eq', $post['season']];
        }
        if(isset($post['dep_id']) && $post['dep_id'] != ""){
            $where[] = ['plan.plan_dep_id', 'eq', $post['dep_id']];
        }
        if(isset($post['specialty_id']) && $post['specialty_id'] != ""){
            $where[] = ['plan.plan_specialty_id', 'eq', $post['specialty_id']];
        }
        if(isset($post['class_id']) && $post['class_id'] != ""){
            $where[] = ['plan.plan_code', 'eq', $post['class_id']];
        }
        if(isset($post['dir']) && $post['dir'] != ""){
            $where[] = ['plan.plan_dir', 'eq', $post['dir']];
        }

        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = 'bm.bmdm ASC, zy.zydm ASC, plan.plan_grade ASC, plan.plan_degree_id ASC';
        return $result;
    }


    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        return $list;
    }

    /**
     *  修改关联
     * User:tony
     * @param $data
     * @return array
     */
    public function saveData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];
        
        // 清理原有记录
        Db::startTrans();
        $this->where(['plan_code'=>$data['planCode']])->delete();
        
        $classIds = explode(',', $data['params']);
        $items     = [];
        // 生成申请明细
        for ($i = 0; $i < count($classIds); $i++) {
            if ($classIds[$i]) {
                $item = explode('-', $classIds[$i]);
                $items[] = [
                    'plan_code'   => $data['planCode'],
                    'bjdm'        => $item[0],
                    'dir'        => $item[1],
                ];

                $where[]   = ['a.plan_code', 'like',  substr($data['planCode'], 0, 5) . '%'];
                $where[]   = ['a.bjdm', 'eq', $item[0]];
                $where[]   = ['a.dir', 'eq', $item[1]];
                // 这里还需要判断是否已存在关联关系
                $exist = $this->alias('a')
                    ->field("distinct b.plan_class_name")
                    ->join('zl_book_plan b', 'a.plan_code = b.plan_code')
                    ->where($where)->find();

                if($exist){
                    $result['status'] = false;
                    $result['msg'] = '财务部门已存在关联关系('.$exist['plan_class_name'].')，操作失败！';
                    Db::rollback();
                    return $result;
                }
            }
        }

        if (!$this->saveAll($items)) {
            $result['status'] = false;
            $result['msg'] = '保存失败！';
            Db::rollback();
            return $result;
        }
         
        Db::commit();
        
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    }

    public function syncClassList() 
    {
        $model = new Common();
        $model->query("call syncClassList();");

        $result = [
            'status' => true,
            'msg' => '同步成功',
            'data' => []
        ];
        return $result;
    }
}